<template>
  <div class="pay-order">
    <div v-loading="isPaying">
      <div class="order-block">
        <div class="order-title">
          订单详情
          <!-- 这里加一个订单倒计时 -->
          <div class="count-down">
            距离订单失效还有:
            <span id="min">00</span>
            :
            <span id="sec">00</span>
          </div>
        </div>
        <div class="order-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="订单号">{{
              orderInfo.order_id
            }}</el-descriptions-item>

            <el-descriptions-item label="产品名">{{
              orderInfo.good_title
            }}</el-descriptions-item>

            <el-descriptions-item label="产品原价">
              {{ orderInfo.price }}
              元
            </el-descriptions-item>

            <el-descriptions-item label="产品秒杀价">
              <span v-if="orderInfo.seckill_price !== null">{{ orderInfo.seckill_price }} 元</span>
            </el-descriptions-item>

            <el-descriptions-item label="收货人名称">
              {{ orderInfo.receiver_name }}
            </el-descriptions-item>

            <el-descriptions-item label="收货人地址">
              {{ orderInfo.receiver_addr }}
            </el-descriptions-item>

            <el-descriptions-item label="收货人电话号码">
              {{ orderInfo.receiver_phone }}
            </el-descriptions-item>

            <el-descriptions-item label="产品状态">
              <el-tag>未支付</el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="创建时间">
              {{ orderInfo.create_time | dateFormat("yyyy-mm-dd hh:mm:ss") }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div class="pay-way">
        <div class="pay-way-title">支付方式</div>
        <div class="pay-way-img-block">

          <!-- 本地支付 -->
          <button class="pay-way-btn" @click="selectPayWay(0)">
            <img :src="require('@/assets/localBankPay.jpg')" class="pay-way-img" title="本地支付" />
          </button>

          <!-- 支付宝支付 -->
          <button class="pay-way-btn" @click="selectPayWay(1)">
            <img :src="require('@/assets/Alipay.png')" class="pay-way-img" title="支付宝支付" />
          </button>

          <!-- 自主添加其它的支付方式 -->
        </div>
      </div>

      <div class="pay-btn">

        <el-button v-show="new Date() - new Date(this.orderInfo.create_time) <= 1800000 && isPaying" class="go-pay"
          type="warning" disabled>支 付 中</el-button>

        <el-button v-show="new Date() - new Date(this.orderInfo.create_time) <= 1800000 && !isPaying" class="go-pay"
          type="warning" @click="payOrderBtn()">支 付</el-button>


        <el-button v-show="new Date() - new Date(this.orderInfo.create_time) > 1800000" class="go-pay" type="warning"
          disabled>超时订单</el-button>
      </div>
    </div>
    <!-- 支付密码窗口 -->
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" title="请输入支付密码"
      :visible.sync="bankPayOrderDialog" width="20%" @close="handlePayOrderDialogClose()" center>
      <div class="pay-password">
        <el-input v-model="payPassword" type="password" placeholder="请输入支付密码" maxlength="6" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bankPayOrder()" :disabled="isPaying">确认支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { alipayOrder } from "@/api/aliPay";
import { getOrder, checkOrder } from "@/api/order";
import { bankCardPay } from "@/api/bank";

export default {
  name: "PayOrder",

  data() {
    return {
      orderInfo: {},
      startInterval: null,
      payWay: 0,
      bankPayOrderDialog: false,
      payPassword: '',
      isPaying: false,
      isPolling: false, // 轮询检查订单是否完成支付
    };
  },

  created() {
    this.getOrderInfo(this.$route.params.orderId);
  },

  mounted() {
    // 禁止浏览器回退
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", function () {
        history.pushState(null, null, document.URL);
      });
    }
  },

  methods: {
    selectPayWay(val) {
      this.payWay = val
      let btn = document.getElementsByClassName("pay-way-btn");
      for (let i = 0; i < btn.length; i++) {
        btn[i].style.border = "none";
      }
      btn[val].style.border = "1px solid #409eff";
    },

    getOrderInfo(orderId) {
      getOrder(orderId).then((res) => {
        this.orderInfo = res.data;
        document.getElementsByClassName("pay-way-btn")[0].style.border =
          "1px solid #409eff";
        if (new Date() - new Date(this.orderInfo.create_time) <= 1800000) {
          this.startInterval = setInterval(this.countDown, 1000);
        }
      });
    },

    payOrderBtn() {
      if (this.payWay === 0) {
        // 打开对话框，输入支付密码
        this.bankPayOrderDialog = true
      } else {
        alipayOrder(this.orderInfo.order_id).then((res) => {
          if (res) {
            this.isPaying = true
            let newWindow = window.open();

            newWindow.document.write(res);

            if (newWindow.document.forms.length > 0) {
              newWindow.document.forms[0].submit();
            }

            this.checkOrderIsFinished()
          }
        });
      }
    },

    bankPayOrder() {
      this.isPaying = true
      bankCardPay(this.orderInfo.order_id, this.payPassword).then((res) => {
        if (res.code === 200) {
          if (this.startInterval !== null) clearInterval(this.startInterval);
          this.$message.success(res.msg)
          setTimeout(() => {
            this.$router.push("/orderList").catch(() => { });
          }, 3000);
        }
      }).catch(() => {
        this.isPaying = false
      })
    },

    countDown() {
      let count = 1800000 - (Date.now() - new Date(this.orderInfo.create_time));
      let min = parseInt((count % (1000 * 60 * 60)) / (1000 * 60));
      let sec = parseInt((count % (1000 * 60)) / 1000);

      if (min < 10) min = "0" + min;
      if (sec < 10) sec = "0" + sec;
      document.getElementById("min").innerHTML = min;
      document.getElementById("sec").innerHTML = sec;

      if (new Date() - new Date(this.orderInfo.create_time) > 1800000) {
        clearInterval(this.startInterval);
        this.countDownFinish();
      }
    },

    countDownFinish() {
      this.getOrderInfo(this.$route.params.orderId);
      // 倒计时结束, 如果还在支付阶段停止轮询
      this.isPolling = false
    },

    handlePayOrderDialogClose() {
      this.$message.info('订单已取消支付')
      this.isPaying = false
    },

    checkOrderIsFinished() {
      if (this.isPolling) {
        checkOrder(this.orderInfo.order_id).then((res) => {
          if (res.code === 200) {
            if (res.data) {
              if (this.startInterval !== null) clearInterval(this.startInterval);
              this.isPolling = false
              this.$message.success('订单支付成功!')
              setTimeout(() => {
                this.$router.push("/orderList").catch(() => { });
              }, 3000);
            }
          }
        })
      }

      if (this.isPolling) {
        setTimeout(this.checkOrderIsFinished(), 3000)
      }
    },
  },
};
</script>

<style>
.pay-order {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  min-height: 100vh;
  font-size: 18px;
  position: fixed;
}

.order-title,
.pay-way-title {
  height: 35px;
  width: 100%;
  background: #409eff;
  color: white;
  font-size: 1.2em;
  font-weight: bold;
  padding-top: 6px;
  padding-left: 10px;
  line-height: 30px;
}

.count-down {
  display: block;
  float: right;
  margin-right: 3%;
}

.order-info {
  padding-left: 10%;
  padding-right: 10%;
  padding-top: 2%;
  margin-bottom: 20px;
}

.el-descriptions_body {
  width: 70%;
}

.pay-way-img-block {
  height: 90px;
  border-bottom: 1px solid #ebeef5;
  width: 100%;
}

.pay-way-btn {
  margin-top: 15px;
  margin-left: 25px;
  border: none;
  background: white;
}

.pay-way-btn:hover {
  border: 1px solid #409eff !important;
  cursor: pointer;
}

.pay-way-img {
  height: 60px;
  width: 200px;
}

.pay-btn {
  width: 100%;
  height: 45px;
  position: fixed;
  left: 0;
  bottom: 0;
  background: #409eff;
}

.go-pay {
  display: block;
  float: right;
  height: 45px;
  width: 130px;
  font-size: 1em;
  line-height: 1.1em;
}
</style>